<?php
require_once(ROOT_DIR_PATH.'/libs/phpmailer/class.phpmailer.php');
class register extends MX_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Educations_Model');
        $this->load->model('Pages_Model');
        $this->load->model('Jobs_Model');
        $this->load->model('Provinces_Model');
        $this->load->model('util/captcha_model');
        $this->load->model('Members_Model');
    }
    
    public function index()
    {
        $eduModel = new Educations_Model();
        $pageModel = new Pages_Model();
        $jobModel = new Jobs_Model();
        $proModel = new Provinces_Model();
        $captcha = new Captcha_Model();
        $imgCaptcha = $captcha->captcha_generate();

        $content = $this->load->view('sigup/register', array(
            'eduList' => $eduModel->getAllList(),
            'qltv' => $pageModel->getPagesById(2),
            'dksd' => $pageModel->getPagesById(3),
            'job' => $jobModel->getAllList(),
            'provinces' => $proModel->getAllList(),
            'imgCaptcha' => $imgCaptcha,
            ), true);


        $data = array(
            'content' => $content,
            'title' => 'Đăng ký tài khoản',
            'meta_des' => 'Đăng ký tài khoản',
            'meta_key' => 'Đăng ký tài khoản',
            );

        $this->load->view("templates/master", $data);
    }


    public function sigup()
    {
        
        
        if (!$_POST) {
            return redirect(base_url());
        }

        $this->load->model('util/captcha_model');
        $memberModel = new Members_Model();
        if (!$memberModel->checkFormSigup()) {
            return $this->index();
        }
        $captcha = new Captcha_Model();
        $arr = array();
        if (!$captcha->captcha_check()) {
            notify_set_messages('Bạn nhập sai mã bảo vệ', 'captcha');
            return $this->index();
        }
        $email = trim($this->input->post('txtEmail'));
        if ($memberModel->checkMember($email)) {
            notify_set_messages('Email đã tồn tại trong hệ thống', 'captcha');
            return $this->index();
        }
        $mid = $memberModel->addNewMember();
        if ($mid) {
            $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
            $mail->IsSMTP(); // telling the class to use SMTP
            $pageModel = new Pages_Model();    
            $pageContent = $pageModel->getPagesById(4);
            try {
                $emailTo = $email;
                $fullName = $this->input->post('txtFullName');
                $mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
                $mail->Debugoutput = 'error_log';
                $mail->SMTPAuth = true; // enable SMTP authentication
                $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
                $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
                $mail->Port = 465; // set the SMTP port for the GMAIL server
                $mail->Username = "smdrupal@gmail.com"; // GMAIL username
                $mail->Password = "smdrupal1@Abc"; // GMAIL password
                $mail->AddAddress($emailTo, $fullName);
                $mail->SetFrom('info@gmail.com', 'Hieu hoc');
                $mail->AddReplyTo('info@gmail.com', 'Hieu hoc');
                $mail->Subject = $pageContent->title;
                $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
                $htmlBody = $pageContent->contents;
                $urlActive = site_url('active/'.imd5($mid));
                $htmlBody = str_replace('{activelink}', $urlActive, $htmlBody);
                $mail->MsgHTML($htmlBody);
                //$mail->AddAttachment('images/phpmailer.gif');      // attachment
                //$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
                $mail->Send();
                
                redirect('register/complates');
            }
            catch (phpmailerException $e) {
                redirect('register/notcomplate');
            }
            catch (exception $e) {
                redirect('register/notcomplate');
            }
        } else {
            redirect('register/notcomplate');
        }
    }

    public function complates()
    {
        $pageModel = new Pages_Model();
        $pageContent = $pageModel->getPagesById(6);
        $content = $pageContent->contents;
        
        $content = $this->load->view('sigup/complate', array('comp_content' => $content), TRUE);
        $data = array(
            'content' => $content,
            'title' => 'Đăng ký hoàn tất',
            'meta_des' => 'Đăng ký hoàn tất',
            'meta_key' => 'Đăng ký hoàn tất',
            );

        $this->load->view("templates/master", $data);
    }
    
    public function notcomplate()
    {
        $content = $this->load->view('sigup/notcomplate', array(), TRUE);
        $data = array(
            'content' => $content,
            'title' => 'Đăng ký hoàn tất',
            'meta_des' => 'Đăng ký hoàn tất',
            'meta_key' => 'Đăng ký hoàn tất',
            );

        $this->load->view("templates/master", $data);
    }
    
    public function logout()
    {
        $this->session->sess_destroy();
        return redirect('/');
    }
    
    public function login()
    {
        $memberModel = new Members_Model();
        $usr = trim($this->input->post("txtUsr"));
        $pwd = imd5($this->input->post("txtPass"));
        $obj = $memberModel->login($usr, $pwd);

        if (!$obj) {
            $arr['success'] = -1;
        } elseif ($obj->status != 1) {
            $arr['success'] = 0;
            $this->session->sess_destroy();
        } else {
            if (isset($_POST['txtRmb'])) {
                $obj->remember = 1;
            } else {
                $obj->remember = 0;
            }
            $arrUser['login'] = $obj;
            $this->session->set_userdata($arrUser);
            $arr['success'] = 1;

        }
        echo json_encode($arr);
    }

    public function active($code = '')
    {
        $this->load->model('Members_Activecode_Model');
        $actiModel = new Members_Activecode_Model();
        $memberModel = new Members_Model();
        $obj = $actiModel->checkActiveCode($code);
        if ($obj) {
            $actiModel->Active($obj->id);
            $memberModel->Active($obj->mid);
        }
        $pageModel = new Pages_Model();
        $pageContent = $pageModel->getPagesById(5);
        $activeContent = $pageContent->contents;
        $content = $this->load->view('sigup/active', array('activeContent' => $activeContent), TRUE);
        $data = array(
            'content' => $content,
            'title' => 'Đăng ký hoàn tất',
            'meta_des' => 'Đăng ký hoàn tất',
            'meta_key' => 'Đăng ký hoàn tất',
            );

        $this->load->view("templates/master", $data);
    }
    
    public function forgot()
    {
        $content = $this->load->view('sigup/forgot', array(), TRUE);
        $data = array(
            'content' => $content,
            'title' => 'Quên mật khẩu',
            'meta_des' => 'Quên mật khẩu',
            'meta_key' => 'Quên mật khẩu',
            );

        $this->load->view("templates/master", $data);
    }
    
    public function forgot_submit()
    {
        if (!$_POST) {
            return redirect('/');
        }
        $email = $this->input->post('email');

        $memModel = new Members_Model();
        $obj = $memModel->checkMemberIsActive($email);
       
        $status = $obj->status;
        if ($status == -1) {
           $info = 'Email không tồn tại trong hệ thống';
        } elseif ($status == 0) {
           $info = 'Email tài khoản chưa được active';
        } elseif ($status == 2) {
           $info = 'Tài khoản đang bị khoá, xin vui lòng liên hệ với admin để được mở khoá!';
        } else {
            $this->load->model('Members_Activecode_Model');
            $actiModel = new Members_Activecode_Model();
            $actiModel->addNewActiveCode($obj->id, 2);
            
            $info = 'Xin vui lòng đăng nhập vào email để reset lại mật khẩu';
        //$info .= site_url('reset/'.imd5($obj->id));
            
            $mail = new PHPMailer(true); 
            $mail->IsSMTP(); 
            try {
                $mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
                $mail->Debugoutput = 'error_log';
                $mail->SMTPAuth = true; // enable SMTP authentication
                $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
                $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
                $mail->Port = 465; // set the SMTP port for the GMAIL server
                $mail->Username = "smdrupal@gmail.com"; // GMAIL username
                $mail->Password = "smdrupal1@Abc"; // GMAIL password
                $mail->AddAddress($email, 'forgot password');
                $mail->SetFrom('info@gmail.com', 'Hieu hoc');
                $mail->AddReplyTo('info@gmail.com', 'Hieu hoc');
                $mail->Subject = 'Quen mat khau tailieu.tructin.com';
                $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
                $htmlBody = 'Quên mật khẩu http://tailieu.hieuhoc.com. Xin vui lòng click vào đường dẫn bên dưới để lấy lại mật khẩu <br>';
                $htmlBody .= site_url('reset/'.imd5($obj->id));
                $htmlBody .= '<br>';
                $mail->MsgHTML($htmlBody);
                //$mail->AddAttachment('images/phpmailer.gif');      // attachment
                //$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
                $mail->Send();
                
                
            }
            catch (phpmailerException $e) {
                
            }
            catch (exception $e) {
                
            }
            
        }
        $content = $this->load->view('sigup/inval', array('info' => $info), TRUE); 
        $data = array(
            'content' => $content,
            'title' => 'Quên mật khẩu',
            'meta_des' => 'Quên mật khẩu',
            'meta_key' => 'Quên mật khẩu',
            );

        $this->load->view("templates/master", $data);
    }
    
    public function reset($code)
    {
        $this->load->model('Members_Activecode_Model');
        $actiModel = new Members_Activecode_Model();
        $obj = $actiModel->checkResetCode($code);
         if ($obj) {
            $_SESSION['forgotId'] = $obj->mid;
            $content = $this->load->view('sigup/reset', array(), TRUE);
            $data = array(
                'content' => $content,
                'title' => 'Quên mật khẩu',
                'meta_des' => 'Quên mật khẩu',
                'meta_key' => 'Quên mật khẩu',
                );
    
            $this->load->view("templates/master", $data);
         } else {
            return redirect('/');
         }
    }
    
    public function reset_submit()
    {
        if (!$_POST) {
            return redirect('/');
        }
        $pass = imd5(trim($this->input->post('pass')));
        $memModel = new Members_Model();
        $memModel->resetpass($_SESSION['forgotId'], $pass);
        
        $this->load->model('Members_Activecode_Model');
        $actiModel = new Members_Activecode_Model();
        $actiModel->Active($_SESSION['forgotId']);
        $info = 'Mật khẩu đã được thay đổi';
        $content = $this->load->view('sigup/inval', array('info' => $info), TRUE); 
        $data = array(
            'content' => $content,
            'title' => 'Quên mật khẩu',
            'meta_des' => 'Quên mật khẩu',
            'meta_key' => 'Quên mật khẩu',
            );

        $this->load->view("templates/master", $data);
    }
    
   
    public function test1()
    {
        $pageModel = new Pages_Model();
        $pageContent = $pageModel->getPagesById(4);
        echo '1';
        print_r($pageContent); die;
    }    
}
